package com.ruoyi.pingjiao.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.pingjiao.domain.Coureassess;
import com.ruoyi.pingjiao.domain.CourseassessName;
import com.ruoyi.pingjiao.domain.Score;
import com.ruoyi.pingjiao.domain.vo.AverageVo;
import com.ruoyi.pingjiao.domain.vo.FinishAverage;
import com.ruoyi.pingjiao.mapper.CourseAssessMapper;
import com.ruoyi.pingjiao.mapper.CourseAssessNameMapper;
import com.ruoyi.pingjiao.mapper.ScoreMapper;
import com.ruoyi.pingjiao.service.CourseAssessService;
import com.ruoyi.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;
import java.util.*;

@Service
public class CourseAssessServiceImpl implements CourseAssessService {
    @Autowired
    private CourseAssessMapper courseAssessMapper;
    @Autowired
    private CourseAssessNameMapper courseAssessNameMapper;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ScoreMapper scoreMapper;
    @Autowired
    protected Validator validator;
    private static final Logger log = LoggerFactory.getLogger(CourseAssessServiceImpl.class);
    @Override
    public List<Coureassess> selectCourseAssessList(Coureassess coureassess) {
        return courseAssessMapper.selectCourseAssessList(coureassess);
    }

    @Override
    public Object getCourseAssessById(Long id) {
        return courseAssessMapper.getCourseAssessById(id);
    }

    @Override
    @Transactional
    public int add(Coureassess coureassess) {
        coureassess.setCreateTime(new Date());
        Long add = courseAssessMapper.add(coureassess);
        CourseassessName courseassessName=new CourseassessName();
//        Long courseAssessId=courseAssessMapper.selectCourseAssessIdByCourseAssess(coureassess.getCourseassess());
        courseassessName.setCoureassessId(coureassess.getId());
        courseassessName.setCourseId(coureassess.getCourseId());
        courseassessName.setTeacherId(Long.valueOf(coureassess.getTeacherId()));
        courseAssessNameMapper.add(courseassessName);
        return 1;
    }

    @Override
    public int update(Coureassess coureassess) {
        coureassess.setUpdateTime(new Date());
        return courseAssessMapper.update(coureassess);
    }

    @Override
    @Transactional
    public int delete(Long[] id) {
        courseAssessMapper.delete(id);
        courseAssessNameMapper.deleteByCourseAssessId(id);
        return 1;
    }

    @Override
    public String importDate(List<Coureassess> list, boolean updateSupport, String username) {
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (Coureassess course : list)
        {
            try
            {
                // 验证是否存在这个用户
//                SysUser u = courseMapper.selectCourseByCourseId(user.getUserName());
//                if (StringUtils.isNull(u))
                if (!StringUtils.isNull(course))
                {
                    BeanValidators.validateWithException(validator, course);
//                    user.setPassword(SecurityUtils.encryptPassword(password));
                    course.setCreateBy(username);
                    courseAssessMapper.add(course);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + "课程目标" + " 导入成功");
                }
//                else if (isUpdateSupport)
//                {
//                    BeanValidators.validateWithException(validator, course);
////                    checkUserAllowed(u);
////                    checkUserDataScope(u.getUserId());
////                    course.setUserId(u.getUserId());
//                    course.setUpdateBy(operName);
////                    courseMapper.updateCourse(course);
//                    courseMapper.insertCourse(course);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、账号 " + course.getCourseName() + " 更新成功");
//                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + "课程目标" + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + "课程目标" + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public ArrayList<Coureassess> list(Integer courseId) {
        return courseAssessMapper.list( courseId);
    }

    @Override
    public List<Coureassess> selectPercentList() {
        return courseAssessMapper.selectPercentList();
    }


    //通过教师Id查询出该教师下的课程目标数
    public int countByTeacherId(Long teacherId) {
        return courseAssessMapper.countByTeacherId(teacherId);
    }
    //查询最大平均值中的目标
    public String selectCourseassessMaxByCourseId(Long courseId) {
        return courseAssessMapper.selectCourseassessMaxByCourseId(courseId);
    }
    //查询最小平均值中的目标
    public String selectCourseassessByMin(Long courseId){
        return courseAssessMapper.selectCourseassessByMin(courseId);
    }
    //计算总达成值及分布率
    public List<Coureassess> caluationAverage(Integer courseId){

        Map<String,Object>map=new HashMap<>();
        map.put("courseId",courseId);

        //        int i= scoreMapper.countStudentByTeacherId(teacherId);
//        finishAverage.setAverageRate(finishAverage.getFinishAverage()/i);
        return courseAssessMapper.statisticsAverage(map);
    }
    //查询课程目标达成情况
    public Coureassess selectCourseassessInfo(Long courseId,Integer id){
        Map<String,Object> map=new HashMap<>();
        map.put("courseId",courseId);
        map.put("id",id);
        return courseAssessMapper.selectCourseassessInfo(map);
    }

    @Override
    public List<Coureassess> selectInfoByTeacherId(Long teacherId) {
        return courseAssessMapper.selectInfoByTeacherId(teacherId);
    }

    @Override
    public AverageVo selectAverage(Long courseId) {
        return courseAssessMapper.selectAverage(courseId);
    }

    @Override
    public List<Coureassess> getAverageByCourseId(Integer courseId) {
        return courseAssessMapper.getAverageByCourseId(courseId);
    }

    @Override
    public List<Coureassess> getScoreByCourseId(Integer courseId) {
//        List<Score> scoreByCourseId = scoreMapper.getScoreByCourseId(courseId);
        List<Coureassess>coureassessList=new ArrayList<>();
        List<Coureassess>coureassesses= courseAssessMapper.selectCourseAssessByCourseId(courseId);
        for (Coureassess c:coureassesses
             ) {
            List<Double>scores= scoreMapper.getScoreById(c.getId());
            Coureassess coureassess=new Coureassess();
            BeanUtils.copyProperties(c,coureassess);
            coureassess.setScores(scores);
            coureassessList.add(coureassess);
        }
        System.out.println("coureassessesList = " + coureassessList);
        return coureassessList;
    }
}
